package com.danan.collection.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.interceptor.Interceptor;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

public class TimeAndTableNameInterceptor implements Interceptor {

    /*
        拦截器作用：
                1.获取数据时间，解决数据漂移问题
                2.获取表名，在HDFS创建目录
    */

    @Override
    public void initialize() {

    }

    @Override
    public Event intercept(Event event) {
        String body = new String(event.getBody(), StandardCharsets.UTF_8);
        JSONObject jsonObject = JSON.parseObject(body);
        String table = jsonObject.getString("table");
        String ts = jsonObject.getString("ts");
        Map<String, String> headers = event.getHeaders();
        headers.put("timestamp", ts + "000"); //Maxwell采集的时间戳单位是秒
        headers.put("tableName",table);
        return event;
    }

    @Override
    public List<Event> intercept(List<Event> list) {
        for (Event event : list) {
            intercept(event);
        }
        return list;
    }

    @Override
    public void close() {

    }
    public static class Builder implements Interceptor.Builder{

        @Override
        public Interceptor build() {
            return new TimeAndTableNameInterceptor();
        }

        @Override
        public void configure(Context context) {

        }
    }
}
